import { createUniFetch } from 'uni-app-fetch'
import { useUserStore } from '@/stores/user'
const tabBarPagePaths = [
  'pages/task/index',
  'pages/message/index',
  'pages/my/index',
]

export const uniFetch = createUniFetch({
  loading: { title: '正在加载...' },
  baseURL: 'https://slwl-api.itheima.net',
  intercept: {
    // 请求拦截器
    request(options) {
      const userStore = useUserStore()
      // 自定义头信息，来传递token数据
      const defautHeader = {
        Authorization: userStore.token,
      }
      options.header = Object.assign({}, defautHeader, options.header)
      return options
    },
    response({ statusCode, data }) {
      // 判断响应结果的状态码是不是401
      if (statusCode === 401) {
        const pageStack = getCurrentPages()
        const currentPage = pageStack[pageStack.length - 1]
        const redirectURL = currentPage.route
        const routeType = tabBarPagePaths.includes(redirectURL)
          ? 'switchTab'
          : 'redirectTo'
        uni.redirectTo({
          url: `/pages/login/index?redirectURL=/${redirectURL}&routeType=${routeType}`,
        })
      }
      return data
    },
  },
})
